package com.zhihesj.anan.system.controller;

import cn.hutool.core.convert.Convert;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.provider.DynamicDataSourceProvider;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhihesj.anan.message.Message;
import com.zhihesj.anan.message.MessageCodeEnum;
import com.zhihesj.anan.security.JwtTokenUtil;
import com.zhihesj.anan.system.entity.*;
import com.zhihesj.anan.system.mapper.LoginMapper;
import com.zhihesj.anan.system.service.*;
import com.zhihesj.anan.system.vo.UserAuthsVo;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


/**
 * @author Administrator
 */
@RestController
public class LoginController {

    @Value("${default.img}")
    private String default_img;

    @Autowired
    @Qualifier("jwtUserDetailsService")
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private UsersService usersService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserAuthsService userAuthsService;

    @Autowired
    private UserDeptService userDeptService;

    @Autowired
    private LoginMapper loginMapper;

    /**
     * 因为项目是前后端分离，这里的login方法可有可无，因为不会经过这里
     * @param sysUser
     * @param request
     * @return
     */
//    @PostMapping("/login")
//    @ApiOperation(value = "获取用户详细信息",notes = "根据URL的ID来获取用户详细信息")
//    public Message login(@RequestBody SysUser sysUser, HttpServletRequest request){
//        final UserDetails userDetails = userDetailsService.loadUserByUsername(sysUser.getUsername());
//
//        final String token = jwtTokenUtil.generateToken(userDetails);
//        return Message.token(token);
//    }

    /**
     * 因为项目是前后端分离，这里的logout方法可有可无，因为不会经过这里
     * @param
     * @param
     * @return
     */
    @GetMapping("/test/mysql")
    @DS("shiro_demo")
    public Message mysql(){
        List<String> muiscNames = loginMapper.findMuiscNames();
        return Message.success(muiscNames);
    }

    @GetMapping("/test/oracle")
    @DS("orcl")
    public Message oracle(){
        List<String> muiscNames = loginMapper.findOracleHelp();
        return Message.success(muiscNames);
    }

    @GetMapping("/test/sqlServer")
    @DS("renli")
    public Message sqlServer(){
        List<String> muiscNames = loginMapper.findSqlServerHelp();
        return Message.success(muiscNames);
    }

    /**
     * 用户POST方式注册
     * @param userAuthsVo
     * @return
     */
    @Transactional
    @PostMapping("/register")
    @ApiOperation(value = "注册",notes = "根据用户注册信息进行注册")
    public Message register(@RequestBody UserAuthsVo userAuthsVo){
        System.out.println(userAuthsVo.toString());
        if (userAuthsVo.getIdentifier() == null) {
            return Message.setResult(MessageCodeEnum.USERNAME_IS_NULL);
        }else if (userAuthsVo.getCredential()==null){
            return Message.setResult(MessageCodeEnum.PASSWORD_IS_NULL);
        }
        try {
            Users users = new Users();
            users.setNickName(userAuthsVo.getIdentifier());
            users.setAvatar(default_img);
            if (usersService.save(users)){
                userAuthsVo.setUserId(users.getId());
                userAuthsVo.setIdentityType("username");
                userAuthsVo.setCredential(new BCryptPasswordEncoder().encode(userAuthsVo.getCredential()));
                userAuthsService.save(Convert.convert(UserAuths.class, userAuthsVo));
                // 所属部门设置
                UserDept userDept = new UserDept();
                userDept.setUserId(userAuthsVo.getUserId());
                userDept.setDeptId(userAuthsVo.getDeptId());
                userDeptService.save(userDept);
                // 所属权限
                QueryWrapper<Role> wrapper = new QueryWrapper<>();
                wrapper.eq("is_default", 1);
                Role role = roleService.getOne(wrapper);
                UserRole userRole = new UserRole();
                userRole.setUserId(users.getId());
                userRole.setRoleId(role.getRoleId());
                userRoleService.save(userRole);
            }
        }catch (Exception e){
            return Message.error(e.getMessage());
        }
        return Message.success(MessageCodeEnum.SUCCESS);
    }

}